//
//  STLSliderAndButtons.m
//  SoulMusic
//
//  Created by DJtd on 16/4/5.
//  Copyright © 2016年 DJtd. All rights reserved.
//

#import "STLSliderAndButtons.h"

@interface STLSliderAndButtons ()

@property (nonatomic, strong) UIButton *startButton;
@property (nonatomic, strong) UIButton *bigButton;
@property (nonatomic, strong) UISlider *playSlider;
@property (nonatomic, strong) UILabel *timeLabel;


@property (nonatomic, strong) AVPlayerLayer *playerLayer;
@property (nonatomic, strong) UIView *playView;
@property (nonatomic, strong) UIView *descView;
@property (nonatomic, strong) UIImageView *imView;

@property (nonatomic, strong) NSString *url;

@end

@implementation STLSliderAndButtons
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (instancetype)initWithFrame:(CGRect)frame withIndextPathNUM:(NSInteger)NUM withType_OneIsYuedan_TwoIsMV:(NSInteger)type withNSMutableArray:(NSMutableArray *)MVArray {
    self = [super initWithFrame:frame];
    if (self) {
        //
        self.avPlayer = [STLAvPlayer shareAVPlayer];
        
        //防止进入多个页面后数组膨胀
        [self.avPlayer.MVList removeAllObjects];
        self.avPlayer.MVList = [NSMutableArray arrayWithArray:MVArray];
        self.avPlayer.indexPathNum = NUM;
        self.avPlayer.pageType = type;
        
        //
        self.playView = [[UIView alloc] initWithFrame:self.bounds];
        self.playView.backgroundColor = [UIColor blackColor];
        [self addSubview:self.playView];
        //

        
        Reachability *wiFi = [Reachability reachabilityForLocalWiFi];
        Reachability *_3G = [Reachability reachabilityForInternetConnection];
        if ([wiFi isReachableViaWiFi] == 1 || [_3G isReachable] == 1) {
            [MBProgressHUD showHUDAddedTo:self.playView animated:YES];
            if (self.avPlayer.MVList.count != 0) {
                [self.imView removeFromSuperview];
                [self creatMVPlay];
                [self creatPage];
            } else {
                [self.playView removeFromSuperview];
                self.imView = [[UIImageView alloc] initWithFrame:self.bounds];
                [self addSubview:self.imView];
                self.imView.image = [UIImage imageNamed:@"wu"];
            }
            
        } else {
            [MBProgressHUD showAlertView:@"" andMessage:@"网络错误"];
        }
        
        
       //
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startAndPauseBug) name:@"pause" object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(judgeTypeSmall) name:@"yes" object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(progress) name:@"progress" object:nil];
        
        [MBProgressHUD hideHUDForView:self.playView animated:YES];

    }
    return self;
}



- (void)creatPage {
    //////////
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
    self.playerLayer.frame = self.playView.bounds;
    
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    
    [self.playView.layer addSublayer:self.playerLayer];
    //////////
    self.descView = [[UIView alloc] initWithFrame:CGRectMake(0, self.bounds.size.height - 30, self.bounds.size.width, 30)];
    self.descView.backgroundColor = [UIColor blackColor];
    self.descView.alpha = 0.8;
    [self.playView addSubview:self.descView];
    //
    self.startButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.startButton.frame = CGRectMake(10, 2, 26, 26);
    [self.startButton addTarget:self action:@selector(startAndPause) forControlEvents:UIControlEventTouchUpInside];
    if (self.avPlayer.isPlayer == YES) {
        [self.startButton setImage:[[UIImage imageNamed:@"play"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    } else {
        [self.startButton setImage:[[UIImage imageNamed:@"pause"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    }
    
    
    //
    self.bigButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.bigButton.frame = CGRectMake(self.descView.bounds.size.width - 30, 2, 26, 26);
    [self.bigButton setImage:[[UIImage imageNamed:@"bigandsmall"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [self.bigButton addTarget:self action:@selector(bigAndSmall) forControlEvents:UIControlEventTouchUpInside];
    
    //
    self.avPlayer.progressView.frame = CGRectMake(46 + 2, 2, self.descView.bounds.size.width - 26 * 5 - 20 - 4, 26);
    
    
    
    //slider
    self.playSlider = [[UISlider alloc] initWithFrame:CGRectMake(46, 2, self.descView.bounds.size.width - 26 * 5 - 20, 26)];
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.playSlider.width + 46, 0, 26 * 3, 30)];
    self.timeLabel.font = [UIFont systemFontOfSize:12];
    self.timeLabel.textColor = [UIColor whiteColor];
    self.timeLabel.textAlignment = NSTextAlignmentCenter;
    //设置最大最小值
    self.playSlider.maximumValue = 1.0f;
    self.playSlider.minimumValue = 0.0f;
    
    
    self.avPlayer.progressView.center = self.playSlider.center;
#pragma mark - timer
    self.timer =  [NSTimer scheduledTimerWithTimeInterval:0.5f  target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
    
    
    [self.playSlider setThumbImage:[UIImage imageNamed:@"slider"] forState:UIControlStateNormal];
    self.playSlider.minimumTrackTintColor = [UIColor colorWithRed:8/255.0 green:146/255.0 blue:114/255.0 alpha:1];
    self.playSlider.maximumTrackTintColor = [UIColor colorWithRed:8/255.0 green:146/255.0 blue:114/255.0 alpha:0];

    [self.descView addSubview:self.timeLabel];
    [self.descView addSubview:self.startButton];
    [self.descView addSubview:self.bigButton];
    [self.descView addSubview:self.avPlayer.progressView];
    [self.descView addSubview:self.playSlider];
    
    //slider 点击事件
    [self.playSlider addTarget:self action:@selector(sliderAction) forControlEvents:UIControlEventValueChanged];
    
    // 让控件隐藏
    if (self.descView.hidden == NO) {
        self.timerHidden =  [NSTimer scheduledTimerWithTimeInterval:5.0f  target:self selector:@selector(dispearAction) userInfo:nil repeats:NO];
    }
}

- (void)dispearAction {
    self.descView.hidden = YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (self.descView.hidden == YES) {
        self.descView.hidden = NO;
        
        [self.timerHidden invalidate];
        self.timerHidden = nil;
        self.timerHidden =  [NSTimer scheduledTimerWithTimeInterval:5.0f  target:self selector:@selector(dispearAction) userInfo:nil repeats:NO];
    } else if (self.descView.hidden == NO) {
        self.descView.hidden = YES;
    }
}





#pragma mark - 暂停
- (void)startAndPause {
    if (self.avPlayer.currentItem.duration.value) {
        if (self.avPlayer.isPlayer == NO) {
            [self.startButton setImage:[[UIImage imageNamed:@"play"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
            [self.avPlayer play];
            self.avPlayer.isPlayer = YES;
        } else if (self.avPlayer.isPlayer == YES) {
            [self.startButton setImage:[[UIImage imageNamed:@"pause"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
            [self.avPlayer pause];
            self.avPlayer.isPlayer = NO;
        }
    }
}

- (void)startAndPauseBug {
        if (self.avPlayer.isPlayer == YES) {
            [self.startButton setImage:[[UIImage imageNamed:@"play"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        } else if (self.avPlayer.isPlayer == NO) {
            [self.startButton setImage:[[UIImage imageNamed:@"pause"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        }
}
#pragma mark - 全屏
- (void)bigAndSmall {
    
    if (self.avPlayer.currentItem.duration.value) {
    
        [self.bigDelegate bigOrSmall];
    
    }
}



- (void)progress {
    self.avPlayer.progressView.frame = CGRectMake(46 + 2, 2, self.descView.bounds.size.width - 26 * 5 - 20 - 4, 26);
    
    self.avPlayer.progressView.center = self.playSlider.center;
    [self.descView addSubview:self.avPlayer.progressView];
    [self.descView bringSubviewToFront:self.playSlider];
}







#pragma mark - slider事件
- (void)sliderAction {
    //    CMTimeMakeWithSeconds
    //    参数1:跳转到的时间
    //    参数2:每秒多少帧 （fps）
    if (self.avPlayer.currentItem.duration.value) {
        [self.avPlayer seekToTime:CMTimeMakeWithSeconds(self.avPlayer.currentItem.duration.value / self.avPlayer.currentItem.duration.timescale * self.playSlider.value, self.avPlayer.currentTime.timescale) completionHandler:^(BOOL finished) {
            [self.startButton setImage:[[UIImage imageNamed:@"play"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
            self.avPlayer.isPlayer = YES;
            [self.avPlayer play];
            
        }];
    }
}

#pragma mark - timer action
- (void)timeAction {
    
    CMTime presentTime = self.avPlayer.currentItem.currentTime;
    
    CMTime totalTime = self.avPlayer.currentItem.duration;
    
    CGFloat presentFloatTim = (CGFloat)presentTime.value/presentTime.timescale;
    
    CGFloat totalFloatTim = (CGFloat)totalTime.value / totalTime.timescale;
    
    self.playSlider.value = presentFloatTim / totalFloatTim;
    
    NSDate *presentDate = [NSDate dateWithTimeIntervalSince1970:presentFloatTim];
    NSDate *totalDate = [NSDate dateWithTimeIntervalSince1970:totalFloatTim];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    if (totalFloatTim / 3600 >= 1) {
        [formatter setDateFormat:@"HH:mm:ss"];
    }else {
        [formatter setDateFormat:@"m:ss"];
    }
    
    
    NSString *presentStrTime = [formatter stringFromDate:presentDate];
    NSString *totalStrTime = [formatter stringFromDate:totalDate];
    //
    if (totalFloatTim <= 0) {
        totalStrTime = @"00:00";
    }
    //
    
    NSString *string = [NSString stringWithFormat:@"%@/%@", presentStrTime, totalStrTime];
    
    self.timeLabel.text = string;
    
    
    //
    
    
    
}






#pragma mark - 播放模式
- (void)judgeTypeSmall {
    
        if (self.avPlayer.changeItem == 0) {
            [self typeWithRound];
        }
        else if (self.avPlayer.changeItem == 1) {
            [self typeWithOnlyOne];
        }
        else if (self.avPlayer.changeItem == 2) {
            [self typeWithRandom];
        }
        
        NSLog(@"--------即将播放第 %ld 首mv", (long)self.avPlayer.indexPathNum);
}


#pragma mark - 顺序
- (void)typeWithRound {
    if (self.avPlayer.MVList.count == 1) {
        
        [self creatMVPlay];
        
    } else {
        [self backMV];
    }
}
#pragma mark - 单曲
- (void)typeWithOnlyOne {
    
    [self creatMVPlay];
}
#pragma mark - 随机
- (void)typeWithRandom {
    if (self.avPlayer.MVList.count == 1) {
        
        [self creatMVPlay];
    } else {
        [self backMV];
    }
}
#pragma mark - 上一曲
- (void)frontMV {
    if (self.avPlayer.isRadom == YES) {
        self.avPlayer.indexPathNum = arc4random()%(self.avPlayer.MVList.count - 1);
        
    } else {
        if (self.avPlayer.indexPathNum == 0) {
            self.avPlayer.indexPathNum = self.avPlayer.MVList.count - 1;
        } else {
            self.avPlayer.indexPathNum -= 1;
        }
    }
    if (self.avPlayer.isPlayer == NO) {
        [self.startButton setImage:[[UIImage imageNamed:@"pausebig"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        self.avPlayer.isPlayer = YES;
    }
    
    [self creatMVPlay];
    
}


#pragma mark - 下一曲
- (void)backMV {
    
    if (self.avPlayer.isRadom == YES) {
        self.avPlayer.indexPathNum = arc4random()%(self.avPlayer.MVList.count - 1);
        
    } else {
        if (self.avPlayer.indexPathNum == (self.avPlayer.MVList.count - 1)) {
            self.avPlayer.indexPathNum = 0;
        } else {
            self.avPlayer.indexPathNum += 1;
        }
    }
    if (self.avPlayer.isPlayer == NO) {
        [self.startButton setImage:[[UIImage imageNamed:@"pausebig"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        self.avPlayer.isPlayer = YES;
    }
    
    [self creatMVPlay];
}







//#pragma mark - 播放mv
- (void)creatMVPlay {
    Reachability *wiFi = [Reachability reachabilityForLocalWiFi];
    Reachability *_3G = [Reachability reachabilityForInternetConnection];
    if ([wiFi isReachableViaWiFi] == 1 || [_3G isReachable] == 1) {
        [MBProgressHUD showHUDAddedTo:self.playView animated:YES];
        if (self.avPlayer.MVList.count != 0) {
            
            [self.imView removeFromSuperview];
            if (self.avPlayer.pageType == 1) {
                self.homeModel = self.avPlayer.MVList[self.avPlayer.indexPathNum];
                
                switch (self.avPlayer.changeType) {
                    case 0:
                    {
                        if (self.homeModel.url) {
                            [self.avPlayer playWithUrl:self.homeModel.url];
                        }
                        //                else if (self.homeModel.uhdUrl) {
                        //                    [self.avPlayer playWithUrl:self.homeModel.uhdUrl];
                        //                }
                        NSLog(@"当前播放的是普清");
                    }
                        break;
                    case 1:
                    {
                        if (self.homeModel.hdUrl) {
                            [self.avPlayer playWithUrl:self.homeModel.hdUrl];
                        } else if (self.homeModel.url) {
                            [self.avPlayer playWithUrl:self.homeModel.url];
                        }
                        //                else if (self.homeModel.uhdUrl) {
                        //                    [self.avPlayer playWithUrl:self.homeModel.uhdUrl];
                        //                }
                        NSLog(@"当前播放的是高清");
                    }
                        break;
                    case 2:
                    {
                        if (self.homeModel.shdUrl) {
                            [self.avPlayer playWithUrl:self.homeModel.shdUrl];
                        } else if (self.homeModel.hdUrl) {
                            [self.avPlayer playWithUrl:self.homeModel.hdUrl];
                        } else if (self.homeModel.url) {
                            [self.avPlayer playWithUrl:self.homeModel.url];
                        }
                        //                else if (self.homeModel.uhdUrl) {
                        //                    [self.avPlayer playWithUrl:self.homeModel.uhdUrl];
                        //                }
                        NSLog(@"当前播放的是超清");
                    }
                        break;
                    default:
                        break;
                }
                
                
                
                [self.avPlayer play];
                self.avPlayer.isPlayer = YES;
            }
            
            else if (self.avPlayer.pageType == 2) {
                self.channelModel = self.avPlayer.MVList[self.avPlayer.indexPathNum];
                
                switch (self.avPlayer.changeType) {
                    case 0:
                    {
                        if (self.channelModel.url) {
                            [self.avPlayer playWithUrl:self.channelModel.url];
                        }
                        //                else if (self.channelModel.uhdUrl) {
                        //                    [self.avPlayer playWithUrl:self.channelModel.uhdUrl];
                        //                }
                        NSLog(@"当前播放的是普清");
                    }
                        break;
                    case 1:
                    {
                        if (self.channelModel.hdUrl) {
                            [self.avPlayer playWithUrl:self.channelModel.hdUrl];
                        } else if (self.channelModel.url) {
                            [self.avPlayer playWithUrl:self.channelModel.url];
                        }
                        //                else if (self.channelModel.uhdUrl) {
                        //                    [self.avPlayer playWithUrl:self.channelModel.uhdUrl];
                        //                }
                        NSLog(@"当前播放的是高清");
                    }
                        break;
                    case 2:
                    {
                        if (self.channelModel.shdUrl) {
                            [self.avPlayer playWithUrl:self.channelModel.shdUrl];
                        } else if (self.channelModel.hdUrl) {
                            [self.avPlayer playWithUrl:self.channelModel.hdUrl];
                        } else if (self.channelModel.url) {
                            [self.avPlayer playWithUrl:self.channelModel.url];
                        }
                        //                else if (self.homeModel.uhdUrl) {
                        //                    [self.avPlayer playWithUrl:self.channelModel.uhdUrl];
                        //                }
                        NSLog(@"当前播放的是超清");
                    }
                        break;
                    default:
                        break;
                }
                
                
                [self.avPlayer play];
                self.avPlayer.isPlayer = YES;
            }

            
        [MBProgressHUD hideHUDForView:self.playView animated:YES];
        //通知当前播放的为第几个
        [[NSNotificationCenter defaultCenter] postNotificationName:@"gg" object:[NSNumber numberWithInteger:self.avPlayer.indexPathNum]];
            
            
        } else {
            [self.playView removeFromSuperview];
            self.imView = [[UIImageView alloc] initWithFrame:self.bounds];
            [self addSubview:self.imView];
            self.imView.image = [UIImage imageNamed:@"wu"];
            [MBProgressHUD hideHUDForView:self.playView animated:YES];
        }
        
    } else {
        [MBProgressHUD showAlertView:@"" andMessage:@"网络错误"];
    }
    
    
}








@end













